# -*- encoding: utf-8 -*-
import flask
from flask import request
import json
import requests
import time
import hmac
import base64
import hashlib

server = flask.Flask(__name__)
server.debug = True


@server.route("/", methods=['post'])
def run():
    post_sign = request.headers.get("Sign")
    print("请求头中的sign", request.headers.get("Sign"))
    post_timestamp = request.headers.get("Timestamp")
    print("请求头中的Timestamp", request.headers.get("Timestamp"))
    print (request.__dict__)
    # 得到当前时间戳
    timestamp = str(round(time.time() * 1000))
    # 计算签名
    app_secret = 'PSCUfpo86sV5wW1RexKIGlyoQ_ngpYdnNyT799pda41DKtC2l9GqsHAiDSZFw_j4'
    app_secret_enc = app_secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(post_timestamp, app_secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(app_secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')
    print("根据加密规则生成的sign:", sign)

    # 验证是否来自钉钉的合法请求
    if (post_sign == sign):
        request_data_dict = json.loads(request.get_data())
        print("请求数据:", request_data_dict)
        # 请求用户id
        post_userid = request_data_dict.get("senderId")
        # 请求具体内容，可以根据该字段值写一些逻辑，返回对应内容
        post_message = request_data_dict.get("text").get("content").strip()
        print("请求内容：", post_message)
        # 请求的群机器人webhook
        post_sessionwebhook = request_data_dict.get("sessionWebhook")
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        # 处理消息，组装返回消息格式
        # 这里可以扩展很多逻辑，可以把回复逻辑提取出去
        ms = "这是响应内容，你请求的是：%s" % (post_message)
        message_json = {
            "msgtype": "text",
            "text": {
                "content": ms
            },
            "at": {
                "atDingtalkIds": [post_userid],
                "isAtAll": False
            }
        }
        # 返回发送状态
        info = requests.post(url=post_sessionwebhook, json=message_json, headers=header)
        print(info.text)
    else:
        print("Warning:Not DingDing's post")


if __name__ == '__main__':
    server.run(host="0.0.0.0", port=8083)
